<?php

use Illuminate\Database\Capsule\Manager as DB;

class IndexController extends Yaf_Controller_Abstract
{
    public function init()
    {
        header('Access-Control-Allow-Origin: *');
    }
    //获取所有启用的问卷
    public function indexAction()
    {
        $age = $this->getRequest()->getQuery('age','0');
        $where = " $age >= qu_startage and qu_status = 1 ";

        //获取所有符合条件并启用的问卷
        $que_list = DB::table('questionnaire')->whereRaw($where)->get();

        //获取该用户做过的所有问卷
        $openid = $this->getRequest()->getQuery('openid','0');
        $is_que_list = DB::table("answer")->where('an_openid','=',$openid)->get();

        foreach( $que_list as $key => $val )
        {
            //循环判断用户有没做过这个问卷
            foreach( $is_que_list as $k => $v ){
                if( $v['an_questionnaireid'] == $val['qu_id'] ){
                    $que_list[$key]['is_question'] = 1;
                }
            }

            if( $val['qu_startage'] >= 12 )
            {
                $month = $val['qu_startage'] % 12 ;
                $year = floor( $val['qu_startage'] / 12 ) ;
                $str = "{$year}岁";
                if( $month > 0 )
                {
                    $str .= "{$month}个月";
                }
                $que_list[$key]['qu_startage'] = $str ;
            } else {
                $que_list[$key]['qu_startage'] = $que_list[$key]['qu_startage'] ;
            }
            if( $val['qu_endage'] >= 12 )
            {
                $month = $val['qu_endage'] % 12 ;
                $year = floor( $val['qu_endage'] / 12 ) ;
                $str = "{$year}岁";
                if( $month > 0 )
                {
                    $str .= "{$month}个月";
                }
                $que_list[$key]['qu_endage'] = $str ;
            } else {
                $que_list[$key]['qu_endage'] = $que_list[$key]['qu_endage'] . "个月";
            }
        }
        echo json_encode($que_list);exit;
    }

    //获取某个问卷所有的题目，并拆分成两个数组，一个是最后部份的数组，一个是除了最后部份的数组
    public function topic_infoAction()
    {
        //前面部份的数组
        $front = array();
        //最后部份的数组
        $finally = array();
        //返回数组
        $arr = array();

        $qu_id = $this->getRequest()->getQuery('qu_id','1');
        $where['top_questionnaireid'] = $qu_id ;
        $where['top_status'] = 1;

        //查询出相关的题目
        $topic_list = DB::table('topic')->where($where)->orderBy('top_section','asc')->orderBy('top_order','desc')->get();

        //查出最大值（也就是获取最后一部份的份值）
        $max = DB::table('topic')->where($where)->orderBy('top_section','asc')->max('top_section');
        foreach( $topic_list as $key => $val )
        {
            //获取题目所有选项
            $option_list = DB::table('topic_option')
                ->where('opt_topicid','=',$val['top_id'])
                ->orderBy('opt_id','asc')
                ->get();

            $topic_list[$key]['option_list'] = $option_list;
            //如果是量表题，算出量表的输出数组
            if( $val['top_type'] == 4 )
            {
                $number = array();
//                echo $val['top_minnumber'],'+',$val['top_maxnumber'],'+',$val['top_interval'],'<br>';
                if( $val['top_interval'] == 0 ){
                    $val['top_interval'] = 1;
                }
                if( $val['top_reverse'] == 1 )
                {
                    for ( $i = $val['top_maxnumber'] ; $i >= $val['top_minnumber'] ; $i = $i - $val['top_interval']  )
                    {
                        $number[] = $i;
                    }

                } else {
                    for ( $i = $val['top_minnumber'] ; $i <= $val['top_maxnumber'] ; $i = $i + $val['top_interval']  )
                    {
                        $number[] = $i;
                    }

                }
                $topic_list[$key]['top_number'] = $number;
            }

            //将题目区分开
            if( $val['top_section'] == $max )
            {
                $finally[] = $topic_list[$key];
            } else {
                $front[] = $topic_list[$key];
            }


            $arr['finally'] = $finally;
            $arr['front'] = $front;
            $arr['max'] = $max;
            $arr['top_count'] = count($topic_list);

        }
        echo json_encode($arr);exit;
    }

    //jssdk调用接口信息
    public function jssdkAction()
    {
        $jssdk = new JSSDK("wx1ce23178f9c39d5d", "7db8a233029def0e6dda80a4ddd941eb");
        $signPackage = $jssdk->GetSignPackage();

        echo json_encode($signPackage);exit;
    }

    //获取网站配置信息
    public function settingAction()
    {
        $where['set_status'] = 1;

        $setting_list = DB::table('setting')->where($where)->get();
        echo json_encode($setting_list);exit;
    }

    //将结果录入数据库
    public function resultAction()
    {

        $data['an_questionnaireid'] = $this->getRequest()->getQuery('an_questionnaireid'); //问卷id

        //答题编号
        $where['an_questionnaireid'] = $data['an_questionnaireid'];
        $where['an_status'] = 1;
        $data['an_number'] = DB::table('answer')->where($where)->max('an_number') + 1;

        $data['an_openid'] = $this->getRequest()->getQuery('openid');
        $data['an_nickname'] = $this->getRequest()->getQuery('nickname');
        $data['an_headimgurl'] = $this->getRequest()->getQuery('headimgurl');
        $data['an_addtime'] = time();

        $res = DB::table('answer')->insertGetId($data);

        if($res)
        {
            $arr =  $this->getRequest()->getQuery('arr');

            //添加答题选项
            foreach( $arr as $key => $val )
            {
                if( $val['position'] > 0 )
                {
                    $dataOPT['aop_answerid'] = $res;
                    $dataOPT['aop_topicid'] = $val['aop_topicid'];
                    $dataOPT['aop_position'] = $val['position'];

                    DB::table('answer_option')->insert($dataOPT);
                }
            }

            //添加答题维度
            foreach( $arr as $key => $val )
            {
                if( $val['top_dimension'] > 0 )
                {
                    $dataADI['adi_answerid'] = $res ;
                    $dataADI['adi_dimension'] = (int)$val['top_dimension'];
                    $dataADI['adi_second_dimsion'] = (int)$val['top_second_dimension'];
                    $dataADI['adi_grade'] = (int)$val['opt_grade'];

                    DB::table('answer_dimension')->insert($dataADI);

                }
            }

            echo $res;

        } else {
            echo "0";
        }
        exit;
    }

    //根据答题id获取最差维度的验证码
    public function codingAction()
    {
        $an_id = $this->getRequest()->getQuery('an_id');
        $an_info = DB::table("answer")
            ->leftJoin("dimension","dim_id","=","an_coding")
            ->where("an_id","=",$an_id)
            ->first();

        if( $an_info['an_pay'] == 1 )
        {
            //已经支付就echo 编码
            echo $an_info['dim_coding'];
        }
        else
        {
            //尚未支付
            echo "no_pay";
        }
    }

    //修改答题记录为已支付
    public function payAction()
    {
        $where['an_id'] = $this->getRequest()->getQuery('an_id');
        $data['an_pay'] = 1;

        $res = DB::table("answer")->where($where)->update($data);
        if( $res )
        {
            echo 1;
        }
        else
        {
            echo 2;
        }
    }

    //根据openid和问卷id返回答题id
    public function answer_idAction()
    {
        $where['an_openid'] = $this->getRequest()->getQuery('openid');
        $where['an_questionnaireid'] = $this->getRequest()->getQuery('qu_id');

        $res = DB::table("answer")->where($where)->first();

        if($res)
        {
            echo $res['an_id'];
        }
        else
        {
            echo "no";
        }
    }

    //查出该优惠码是否正确
    public function privilegeAction()
    {
        $code = $this->getRequest()->getQuery("code");
        $an_id = $this->getRequest()->getQuery("an_id");
        $res = DB::table("setting")->where("set_key","=",'set_code')->first();


        if( $res['set_value'] == $code )
        {

            //修改优惠码为已使用 优惠码表废弃掉了
//            $data['co_status'] = 1;
//            $res2 = DB::table("code")->where("co_code","=",$code)->update($data);

            //修改答题为已支付
            $dataAN['an_pay'] = 1;
            $res = DB::table("answer")->where("an_id","=",$an_id)->update($dataAN);

            if( $res )
            {
                echo 1;
            }
            else
            {
                echo 2;
            }

        }
        else
        {
            //没有这个优惠码
            echo 2;
        }
    }

    //根据答题id输出该答题结果
    public function answerAction()
    {
        //获取答题基本信息
        $an_id = $this->getRequest()->getQuery('an_id');
        $answer_info = DB::table("answer")
            ->where("an_id","=",$an_id)
            ->leftJoin("questionnaire","qu_id","=","an_questionnaireid")
            ->first();

        //获取标准分对比的json
        $score = object_array( json_decode(file_get_contents("score.json")));

        //维度输出
        $dim_list = DB::table('dimension')
        ->where("dim_questionid", "=", $answer_info['an_questionnaireid'])
        ->where('dim_father','=',0)
        ->where("dim_status",'=',1)
        ->get();

        //妈妈优势的数组
        $sup_list = array();

        //努力方向的数组
        $eff_list = array();

        //最低分的小维度，获取来和最低大维度对比，然后得出最低分的维度
        $coding = array();
        $coding['num'] = 1000;

        //分数最大的小维度
        $coding['big_num'] = -1000;

        //成绩输出的大维度
        foreach( $dim_list as $key => $val )
        {
            //查出该大维度所有的小维度
            $second_list = DB::table('dimension')
                ->where("dim_questionid", "=", $answer_info['an_questionnaireid'])
                ->where('dim_father', '=', $val['dim_id'])
                ->where("dim_status", '=', 1)
                ->get();

            //循环查出维度所得分数
            foreach( $second_list as $k => $v )
            {
                $number = "0";

                if( $v['dim_scoring'] == 1 )
                {
                    //如果是原始总分
                    $whereSEC['adi_second_dimsion'] = $v['dim_id'];//答题所属小维度等于该小维度的
                    $whereSEC['adi_answerid'] = $answer_info['an_id']; //属于该答题的
                    $number = DB::table('answer_dimension')->where($whereSEC)->sum("adi_grade");
                }
                else if( $v['dim_scoring'] == 2 )
                {
                    //如果是原始平均分
                    $whereSEC['adi_second_dimsion'] = $v['dim_id'];//答题所属小维度等于该小维度的
                    $whereSEC['adi_answerid'] =  $answer_info['an_id']; //属于该答题的
                    $number = DB::table('answer_dimension')->where($whereSEC)->avg("adi_grade");
                }
                else if( $v['dim_scoring'] == 3 )
                {
                    //如果是百分比
                    $whereSEC['adi_second_dimsion'] = $v['dim_id'];//答题所属小维度等于该小维度的
                    $whereSEC['adi_answerid'] = $answer_info['an_id']; //属于该答题的
                    $number = DB::table('answer_dimension')->where($whereSEC)->avg("adi_grade");
                }

                //判断标准差和平均值是否为0
                if($v['dim_mean'] == 0 )
                {
                    $v['dim_mean'] = 1;
                }
                if($v['dim_deviation'] == 0 )
                {
                    $v['dim_deviation'] = 1;
                }

                //算出平均值，看是否标红
                $average = ( $number - $v['dim_mean'] ) / $v['dim_deviation'];

                //记录下分数最低小维度

                if( $number != 0 )
                {
                    if( $coding['num'] > $average  )
                    {
                        $coding['num'] = $average;
                        $coding['dim_id'] = $v['dim_id'];
                        //获得分数最低的小维度的差评语
                        $substitu_bad = $v['dim_bad'];

                    }
                }
                //记录下分数最大小维度
                if( $coding['big_num'] < $average  )
                {
                    $coding['big_num'] = $average;
                    $coding['dim_result_img'] = $v['dim_result_img'];
                    //获得分数最高的小维度的好评语
                    $backups_actor = $v['dim_actor'];
                }

                //如果是百分比，判断number范围是否超出标准分的范围
                if( $v['dim_scoring'] == 3 ){

                    if( $number < -3 )
                    {
                        $number = "-3.00";
                    }

                    if( $number > 3 )
                    {
                        $number = "3.00";
                    }

                    $average = $number;

                    $number = sprintf("%01.2f",$number);
                    $number = $score["$number"];

                }

                //添加进相应评语列表，查看是否标红
                if( $average >= 1 )
                {
                    $average = 1;
                    $sup_list[] = $v['dim_actor'];
                }
                else if( $average < -1 )
                {
                    if( $number != 0 )
                    {
                        $average = 2;
                        $eff_list[] = $v['dim_bad'];
                    }
                }


                //显示的分数
                $second_list[$k]['number'] = round( $number * 1,2);
                //是否标红 $average = 1 为不标红
                $second_list[$k]['average'] = $average;

            }

            $dim_list[$key]['children'] = $second_list;

        }

        //雷达图
        //查出该问卷所有显示在雷达图上的维度
        $radar_list = DB::table("que_radar_dimension")
            ->where("qrd_questionnaireid","=",$answer_info['an_questionnaireid'])
            ->join("dimension","dim_id","=","qrd_dimensionid")
            ->get();

        foreach ( $radar_list as $keys => $value )
        {
            if( $value['dim_father'] == 0 )
            {
                //判断当前循环的大维度是否等于该维度
                foreach( $dim_list as $key => $val )
                {
                    if( $value['dim_id'] == $val['dim_id'] )
                    {
                        //声明一个空值存储该大维度所属的小维度的分数总和
                        $n = 0;
                        $b = 0;
                        foreach( $val['children'] as $k => $v )
                        {
                            if( $v['number'] == 0 )
                            {
                                ++$b;
                            }
                            else
                            {
                                $n += $v['number'];
                            }
                        }

                        if($value['dim_mean'] == 0 )
                        {
                            $value['dim_mean'] = 1;
                        }
                        if($value['dim_deviation'] == 0 )
                        {
                            $value['dim_deviation'] = 1;
                        }

                        //计算出这个维度的分数的标准分
                        $key = round(( ( $n / (count( $val['children'] ) - $b ) ) - $value['dim_mean'] ) / $value['dim_deviation'],2);
                        if( $key < -3 )
                        {
                            $key = "-3.00";
                        }
                        if( $key > 3 )
                        {
                            $key = "3.00";
                        }

                        $key = sprintf("%01.2f",$key);
                        $radar_list[$keys]['radar_number'] = round( $score["$key"] * 1 ,1 ) ;
                    }
                }
            }
            else
            {
                //判断当前循环的小维度是否等于该维度
                foreach( $dim_list as $key => $val )
                {
                    foreach( $val['children'] as $k => $v )
                    {
                       if( $v['dim_id'] == $value['dim_id'] )
                       {

                           if($value['dim_mean'] == 0 )
                           {
                               $value['dim_mean'] = 1;
                           }
                           if($value['dim_deviation'] == 0 )
                           {
                               $value['dim_deviation'] = 1;
                           }

                           $key = round(( $v['number'] - $value['dim_mean'] ) / $value['dim_deviation'],2);

                           if( $key < -3 )
                           {
                               $key = "-3.00";
                           }
                           if( $key > 3 )
                           {
                               $key = "3.00";
                           }

                           $key = sprintf("%01.1f",$key);
                           $radar_list[$keys]['radar_number'] = $score["$key"] * 1;
                       }
                    }
                }
            }
        }

        //妈妈优势评语 先查出所有大维度，然后获取他们的标准分，然后将标准分赋值最大的维度的评语插入在优势评语列表数组的第一个元素，为了方便维度，所以这里写多了一个循环
        $num = -1000; //最高分的一级维度
        $num2 = 1000; //最低分的一级维度
        $num_count = 0; //成绩总分
        $appellation_num = 0; //最好的维度的分数
        $appellation = ''; //最好的维度的妈妈称呼
        $num_cout_number = DB::table("dimension")
            ->where("dim_questionid","=",$answer_info['an_questionnaireid'])
            ->where("dim_status","=",1)
            ->count();

        foreach( $dim_list as $key => $val )
        {
            //声明一个空值存储该大维度所属的小维度的分数总和
            $n = 0;
            $n_c = count($val['children']);
            foreach( $val['children'] as $k => $v )
            {
                if( $v['number'] == 0 )
                {
                    --$num_cout_number;
                    --$n_c;
                }
                else
                {
                    $n += $v['number'];
                    $num_count += $v['number'];
                }

                if ( $v['number'] > $appellation_num )
                {
                    $appellation = $v['dim_appellation'];
                }
            }

            if($val['dim_mean'] == 0 )
            {
                $val['dim_mean'] = 1;
            }
            if($val['dim_deviation'] == 0 )
            {
                $val['dim_deviation'] = 1;
            }


            //计算出该维度的分数
            $num_count += $n / $n_c ;
            //计算出这个维度的分数的标准分(以下部份跟总分计算无关)
            $r = round(( ( $n / count( $val['children'] ) ) - $val['dim_mean'] ) / $val['dim_deviation'],2);

            //判断出最优的大维度
            if( $r > $num )
            {
                $num = $r;
                //最优维度评语
                $mes = $val['dim_actor'];

//                if( $r > $appellation_num )
//                {
//                    $appellation = $val['dim_appellation'];
//                }

            }

            //判断出最差的大维度
            if( $r < $num2 )
            {
                $num2 = $r;
                $mes2 = $val['dim_bad'];

                //获得最差的大维度id和他的维度分数，到时和最差的小维度比较
                $coding2['dim_id'] = $val['dim_id'];
                $coding2['num'] = $r;

                //建议
                $offer = $val['dim_offer'];
            }

        }

        //如果平均值为0
        if( $answer_info['qu_mean'] == 0 )
        {
            $answer_info['qu_mean'] = 1;
        }

        //如果标准差为0
        if( $answer_info['qu_deviation'] == 0 )
        {
            $answer_info['qu_deviation'] = 1;
        }


        //计算总分
        $num_count = round(( ( $num_count / $num_cout_number  ) - $answer_info['qu_mean'] ) / $answer_info['qu_deviation'],2);
        $num_count = sprintf("%01.2f",$num_count);

        //获得该问卷的平均分
        if( $num_count < -3 )
        {
            $num_count = "-3.00";
        }

        if( $num_count > 3 )
        {
            $num_count = "3.00";
        }

        $num_count = round($score["$num_count"] * 1);


        //如果没有标准分好的评语
        if( !$sup_list )
        {
            $sup_list[] = $backups_actor ;
        }

        //插入标准分最大的大维度评语
        $num = sprintf("%01.2f",$num);
        $mes = str_replace("{x%}",$score["$num"],$mes);
        array_unshift($sup_list,$mes);

        //如果没有标准分差的评语
        if( !$eff_list )
        {
            $eff_list[] = $substitu_bad;
        }

        //插入标准分最小的大维度评语
        $num2 = sprintf("%01.2f",$num2);
        $mes2 = str_replace("{x%}",$score["$num2"],$mes2);
        array_unshift($eff_list,$mes2);
        //将标准分最小的维度记录到问卷表中，以备付款后查看
        if( $coding['num'] < $coding2['num'] )
        {
            $dataAN['an_coding'] = $coding['dim_id'];
            DB::table("answer")->where("an_id","=",$an_id)->update($dataAN);
        }
        else
        {
            $dataAN['an_coding'] = $coding2['dim_id'];
            DB::table("answer")->where("an_id","=",$an_id)->update($dataAN);
        }

        //计算出打败了多少位妈妈
        $que_id = $answer_info['an_questionnaireid'];
        $defeat = DB::table("answer_dimension")
            ->leftJoin("answer","an_id","=","adi_answerid")
            ->where("an_questionnaireid","=",$que_id)
            ->groupBy("adi_answerid")
            ->selectRaw('*, sum(adi_grade) as sum')
            ->havingRaw(" sum < ( select sum(adi_grade) from `an_answer_dimension` where adi_answerid = $an_id ) ")
            ->get();
        $defeat = count($defeat);


        $data['dim_list'] = $dim_list; //显示的维度列表详细信息
        $data['radar_list'] = $radar_list; //显示在雷达图上的维度
        $data['answer_info'] = $answer_info; //问卷结果详细信息
        $data['sup_list'] = $sup_list; //优势评语列表
        $data['eff_list'] = $eff_list; //努力方向的评语列表
        $data['defeat'] = $defeat + 543; //打败多少位妈妈
        $data['num_count'] = $num_count; //总分
        $data['offer'] = $offer;//建议
        $data['appellation'] = $appellation; //最优维度的妈妈称呼
        $data['dim_result_img'] = base_url . $coding['dim_result_img']; //分数最大的小维度的字幕云
        $data['headimgurl'] = $answer_info['an_headimgurl'];//做问卷的用户的头像
        echo json_encode($data);exit;

    }

}
